<?php
/**
 *   Joomdiet - administrator/components/models/food.php
 *   Author: Juan Dapena Paz (juan@bittingbits.com)
 *   Copyright (C) 2010 Bitting Bits S.L.
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');

class JoomdietModelFood extends JModel {
    var $_data; // collection of food
    var $_food; // individual food
    var $_pagination;
    
    function __construct()
    {
        parent::__construct();
        
        global $mainframe, $option;
        
        try {
            $array = JRequest::getVar('cid', 0, '', 'array');
            $this->setId((int)$array[0]);
        } catch (Exception $e) {
            // do nothing
        }
        
        // loading pagination support
        $limit = $mainframe->getUserStateFromRequest('global.list.limit',
                                                     'limit',
                                                     $mainframe->getCfg('list_limit'),
                                                     'int');
        $limitstart = JRequest::getVar('limitstart', 0, '', 'int');
        $limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
        $this->setState('limit', $limit);
        $this->setState('limitstart', $limitstart);
    }
    
    // default query constructor
    function _buildQuery() {
        $query = 'SELECT * FROM #__joomdiet_Food';
        return $query;
    }
    
    function setId($id)
    {
        $this->_id = $id;
        $this->_variable = null;
    }
    
    function getData()
    {
        if (empty($this->_data)) {
            $query = $this->_buildQuery();
            if (empty($this->_pagination)) {
                $this->_data = $this->_getList($query);
            } else {
                $this->_data = $this->_getList($query, 
                                               $this->getState('limitstart'),
                                               $this->getState('limit'));
            }
            if (empty($this->_data)) $this->_data = array();
        }
        
        return $this->_data;
    }
    
    function getPagination()
    {
        if (empty($this->_pagination)) {
            jimport('joomla.html.pagination');
            $this->_pagination = new JPagination($this->getTotal(),
                                                 $this->getState('limitstart'),
                                                 $this->getState('limit'));
        }
        
        return $this->_pagination;
    }
    
    function getTotal()
    {
        if (empty($this->_total)) {
            $query = $this->_buildQuery();
            $this->_total = $this->_getListCount($query);
        }
        return $this->_total;
    }
    
    function getFood()
    {
        if ($this->_loadFood()) {
        } else $this->_initFood();
        
        return $this->_food;
    }
    
    function getFoodById($id) {
        $query = 'SELECT * FROM #__joomdiet_Food WHERE id='.$id;
        $this->_db->setQuery($query);
        return $this->_db->loadObject();
    }
    
    function _loadFood()
    {
        if (empty($this->_food))
        {
            $query = 'SELECT * FROM #__joomdiet_Food WHERE id='.$this->_id;
            $this->_db->setQuery($query);
            $this->_food = $this->_db->loadObject();
            
            return (boolean) $this->_food;
        }
    }
    
    function _initFood()
    {
        if (empty($this->_food)) {
            $food = new stdClass();
            $food->id = 0;
            $food->name = null;
            $food->description = null;
            $food->food_category_id = null;
            
            $this->_food = $food;
            return (boolean) $this->_food;
        }
        
        return true;
    }
    
    function store() 
    {
        $this->getFood();
        
        $this->_food->name = JRequest::getVar('food_name');
        $this->_food->description = JRequest::getVar('food_description');
        $this->_food->food_category_id = JRequest::getVar('food_parent_category');
        $this->_food->id = JRequest::getVar('food_id');
        
        if (!$this->_food->id) {
            $query = 'INSERT INTO #__joomdiet_Food'.
                ' (name, description, food_category_id) VALUES'.
                ' ("'.$this->_food->name.'", "'.$this->_food->description.'",'.
                ' '.$this->_food->food_category_id.')';
        } else {
            $query = 'UPDATE #__joomdiet_Food '.
                ' SET name="'.$this->_food->name.'",'.
                ' description="'.$this->_food->description.'",'.
                ' food_category_id='.$this->_food->food_category_id.
                ' WHERE id='.$this->_food->id;
        }
        
        $this->_db->setQuery($query);
        $this->_db->query();
        
        if (!$this->_food->id) {
            return $this->_db->insertid();
        } else return $this->_food->id;
    }
    
    function getModel()
    {
        return $this;
    }
    
    function insert($foodname, $foodcategory)
    {
        $query = 'INSERT INTO #__joomdiet_Food (name, food_category_id) ';
        $query .= 'VALUES ('.$foodname.', "'.$foodcategory.'")';
        $this->_db->setQuery($query);
        echo $this->_db->getQuery($query).'<br />';
        $this->_db->query();
        return $this->_db->insertid();
    }
    
    function delete($id)
    {
        // checking dependencies
        $query = 'SELECT count(*) FROM #__joomdiet_Recipe_food WHERE id_food='.$id;
        $this->_db->setQuery($query);
        $n = $this->_db->loadResult();
        if ($n == 0) {
        
            // deleting food
            $query = 'DELETE FROM #__joomdiet_Food WHERE id='.$id;
            $this->_db->setQuery($query);
            $this->_db->query();
            
            // deleting food variables relations
            $query = 'DELETE FROM #__joomdiet_Food_variable WHERE id_food='.$id;
            $this->_db->setQuery($query);
            $this->_db->query();
            
            return true;
        } else return false;
    }
    
    function exists($id) {
        $query = 'SELECT count(*) FROM #__joomdiet_Food WHERE id='.$id;
        $this->_db->setQuery($query);
        return $this->_db->loadResult();
    }
    
    function update($food) {
        $query = 'UPDATE #__joomdiet_Food SET name="'.$food->name.'"';
        $query .= ', description="'.$food->description.'"';
        $query .= ', food_category_id="'.$food->food_category_id.'"';
        $query .= ' WHERE id='.$food->id;
        $this->_db->setQuery($query);
        $this->_db->query();
        if (isset($food->var_relations) && (count($food->var_relations) > 0)) {
            foreach ($food->var_relations as $key => $var_relation) {
                // var name exists
                $query = 'SELECT id FROM #__joomdiet_Variable WHERE name="'.$key.'"';
                $this->_db->setQuery($query);
                if ($id = $this->_db->loadResult()) {
                    $query = 'SELECT count(*) FROM #__joomdiet_Food_variable';
                    $query .= ' WHERE id_food='.$food->id.' AND';
                    $query .= ' id_variable='.$id;
                    $this->_db->setQuery($query);
                    if ($this->_db->loadResult()) {
                        $query = 'UPDATE #__joomdiet_Food_variable SET amount="'.$food->var_relations[$key].'"';
                        $query .= ' WHERE id_food='.$food_id.' AND id_variable='.$id;
                    } else {
                        $query = 'INSERT INTO #__joomdiet_Food_variable (id_food, id_variable, amount)';
                        $query .= ' VALUES ('.$food->id.', '.$id.', "'.$food->var_relations[$key].'")';
                    }
                    $this->_db->setQuery($query);
                    $this->_db->query();
                }
            }
        }
    }
    
    function add($food) {
        $query = 'INSERT INTO #__joomdiet_Food (name, description, food_category_id)';
        $query .= ' VALUES ("'.$food->name.'", "'.$food->description.'", ';
        $query .= ' '.$food->food_category_id.')';
        $this->_db->setQuery($query);
        $this->_db->query();
        $food->id = $this->_db->insertid();
        if (isset($food->var_relations) && (count($food->var_relations) > 0)) {
            foreach ($food->var_relations as $key => $var_relation) {
                // var name exists
                $query = 'SELECT id FROM #__joomdiet_Variable WHERE name="'.$key.'"';
                $this->_db->setQuery($query);
                if ($id = $this->_db->loadResult()) {
                    $query = 'INSERT INTO #__joomdiet_Food_variable (id_food, id_variable, amount)';
                    $query .= ' VALUES ('.$food->id.', '.$id.', "'.$food->var_relations[$key].'")';
                    $this->_db->setQuery($query);
                    $this->_db->query();
                }
            }
        }
    }
    
    function getExampleData() {
        $query = 'SELECT * FROM #__joomdiet_Food LIMIT 10';
        $this->_db->setQuery($query);
        $foodlist = $this->_db->loadObjectList();
        
        foreach ($foodlist as &$food) {
            $query = 'SELECT * FROM #__joomdiet_Food_variable a';
            $query .= ' INNER JOIN #__joomdiet_Variable b ON a.id_variable=b.id';
            $query .= ' WHERE a.id_food='.$food->id;
            $this->_db->setQuery($query);
            $variables =$this->_db->loadObjectList();
            $food->var_relations = array();
            foreach ($variables as $variable) {
                $food->var_relations[$variable->name] = $variable->amount;
            }
        }
        
        return $foodlist;
    }
}
?>
